/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import negocio.Articulo;
import negocio.Compra;

/**
 *
 * @author JAVA
 */
public class PersistenciaCompra {

    //insertar compra en la bbdd
    public static int insertarCompra(Compra c) {

        int i = 0;
        int idcompra = 0;
        ArrayList<Articulo> listaArticulos = null;
        Connection con = null;
        Statement st = null;
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fAlta = sdf.format(c.getFecha());


        try {


            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://192.168.1.18/videoclub", "cibernos", "1234");
            st = con.createStatement();
            i = st.executeUpdate("insert into compra (id,nombre,nif,fecha) values"
                    + "(0,'" + c.getCliente().getNombre() + "','" + c.getCliente().getDni() + "','" + fAlta + "')");
            ResultSet r=st.executeQuery("select last_insert_id()");
            
            if(r.next()){
                idcompra=r.getInt(1);
            }
                listaArticulos = c.getListaArticulos();
                Iterator it = listaArticulos.iterator();


                while (it.hasNext()) {
                    Articulo a = (Articulo) it.next();
                    i = st.executeUpdate("update articulo set baja='1', disponible='0' where articulo.id=" + a.getId() + ";");

                    i = st.executeUpdate("insert into articuloscomprados (id,idcompra,idarticulo) values"
                            + "(0," + idcompra + "," + a.getId() + ")");
                }
            st.close();
            con.close();


        } catch (SQLException ex) {
            Logger.getLogger(PersistenciaCompra.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PersistenciaCompra.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(PersistenciaCompra.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(PersistenciaCompra.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            return i;
        }
    }
}
